package com.yklx.youke.admin.controller;

import com.yklx.youke.entity.Course;
import com.yklx.youke.admin.service.CourseService;
import com.yklx.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/admin/courses")
public class CourseController {
    
    @Autowired
    private CourseService courseService;
    
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 获取当前用户可访问的课程列表
     */
    @PreAuthorize("hasAuthority('course:read')")
    @GetMapping
    public ResponseEntity<List<Course>> getUserCourses(@RequestHeader("Authorization") String token) {
        try {
            String userId = extractUserIdFromToken(token);
            if (userId == null) {
                return ResponseEntity.status(401).build();
            }
            
            // 根据用户角色返回相应的课程列表
            List<Course> courses = courseService.getUserCourses(userId);
            return ResponseEntity.ok(courses);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 获取所有课程（仅管理员可用）
     */
    @PreAuthorize("hasAuthority('course:read')")
    @GetMapping("/all")
    public ResponseEntity<List<Course>> getAllCourses(@RequestHeader("Authorization") String token) {
        try {
            List<Course> courses = courseService.getAllCourses();
            return ResponseEntity.ok(courses);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 获取单个课程信息
     */
    @PreAuthorize("hasAuthority('course:read')")
    @GetMapping("/{courseId}")
    public ResponseEntity<Course> getCourse(@PathVariable String courseId, @RequestHeader("Authorization") String token) {
        try {
            Course course = courseService.getCourseById(courseId);
            if (course == null) {
                return ResponseEntity.notFound().build();
            }
            return ResponseEntity.ok(course);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 创建新课程
     */
    @PreAuthorize("hasAuthority('course:write')")
    @PostMapping
    public ResponseEntity<Course> createCourse(@RequestBody Course course, @RequestHeader("Authorization") String token) {
        try {
            String userId = extractUserIdFromToken(token);
            // 设置创建者为当前用户
            course.setTeacherId(userId);
            boolean success = courseService.createCourse(course);
            if (success) {
                return ResponseEntity.ok(course);
            } else {
                return ResponseEntity.badRequest().build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 更新课程信息
     */
    @PreAuthorize("hasAuthority('course:write')")
    @PutMapping("/{courseId}")
    public ResponseEntity<Course> updateCourse(@PathVariable String courseId, 
                                               @RequestBody Course course, 
                                               @RequestHeader("Authorization") String token) {
        try {
            course.setCourseId(courseId);
            boolean success = courseService.updateCourse(course);
            if (success) {
                return ResponseEntity.ok(course);
            } else {
                return ResponseEntity.badRequest().build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 删除课程
     */
    @PreAuthorize("hasAuthority('course:write')")
    @DeleteMapping("/{courseId}")
    public ResponseEntity<Void> deleteCourse(@PathVariable String courseId, @RequestHeader("Authorization") String token) {
        try {
            boolean success = courseService.deleteCourse(courseId);
            if (success) {
                return ResponseEntity.ok().build();
            } else {
                return ResponseEntity.badRequest().build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }

    // 以下为辅助方法
    private String extractUserIdFromToken(String token) {
        if (token != null && token.startsWith("Bearer ")) {
            String actualToken = token.substring(7);
            try {
                return jwtUtil.getUserIdFromToken(actualToken);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }


}